/*
 * @Author: yzr
 * @Date: 2023-09-20 17:25:15
 * @LastEditors: yzr
 * @LastEditTime: 2023-10-11 15:56:13
 * @Description:
 * @FilePath: /utilization/src/components/RangePicker/index.tsx
 */
import { useState, forwardRef, useImperativeHandle } from 'react';
import { DatePicker } from 'antd';
import { disabledDate } from '@/utils/antMixin';
import './index.scss';
import classNames from 'classnames';

const { RangePicker } = DatePicker;

const pickerType = [
  {
    label: '按日',
    value: 'date',
    key: 'date',
  },
  {
    label: '按月',
    value: 'month',
    key: 'month',
  },
  {
    label: '按季',
    value: 'quarter',
    key: 'quarter',
  },
  {
    label: '按年',
    value: 'year',
    key: 'year',
  },
];

interface Iprops {
  dateChange?: (date: any, dateString: any) => void;
  defaultDate?: any; //默认日期
  disableDateRef?: any; //自定义disabledDate
  typeChange?: (e: any) => void; //tab选择切换
}

const MyRangePicker = forwardRef((props: Iprops, ref: any) => {
  const {
    dateChange,
    defaultDate,
    disableDateRef = disabledDate,
    typeChange,
  } = props;
  // 时间维度
  const [picker, setPicker] = useState<'date' | 'month' | 'quarter' | 'year'>(
    'date'
  );

  // 日期
  const [day, setDay] = useState<any>();
  const [date, setDate] = useState<string[]>([]);
  const onDateChange = (date: any, dateString: any) => {
    setDate(dateString);
    setDay(date);
    dateChange && dateChange(date, dateString);
  };

  const onTypeChange = (e: any) => {
    setDay(null);
    setPicker(e);
    setDate([]);
    typeChange && typeChange(e);
  };

  useImperativeHandle(ref, () => ({
    picker,
    date,
  }));

  return (
    <div ref={ref}>
      <RangePicker
        picker={picker}
        value={day || defaultDate}
        onChange={onDateChange}
        separator={<span style={{ color: '#bbbcbf' }}>至</span>}
        disabledDate={disableDateRef}
        panelRender={origin => (
          <div>
            <div className="rangePickerTab">
              {pickerType.map(item => {
                return (
                  <span
                    key={item.value}
                    onClick={() => onTypeChange(item.value)}
                    className={classNames(
                      'rangePickerTabItem',
                      item.value === picker && 'rangePickerTabItemActive'
                    )}>
                    {item.label}
                  </span>
                );
              })}
            </div>
            <div>{origin}</div>
          </div>
        )}
      />
    </div>
  );
});

export default MyRangePicker;
